<template>
  <div
    class="pdf-view"
    :class="{ 'pdf-view-fixed': isFullScreen }"
    :style="{ height: pdfViewHeight + 'px' }"
  >
    <div class="pdf-view-header">
      <div
        class="pdf-menu el-icon-s-fold"
        :class="{ active: !isMenu }"
        @click="handleMenuChange()"
      ></div>
      <div class="pdf-page">
        <div class="icon el-icon-arrow-left" @click="changePdfPage(0)"></div>
        <el-input v-model="currentPage" :min="1" :max="pageTotal" @change="pageChange"></el-input>
        <div class="text">/{{ pageTotal || 1 }}</div>
        <div class="icon el-icon-arrow-right" @click="changePdfPage(1)"></div>
      </div>
      <div class="pdf-scale">
        <div class="icon el-icon-minus" @click="scalePage(0)"></div>
        <div class="text">{{ Math.round(pageScale * 100) }}%</div>
        <div class="icon el-icon-plus" @click="scalePage(1)"></div>
      </div>
      <div class="pdf-full edu-icon-quanping" @click="changeFullScreen"></div>
    </div>
    <div v-show="showSpinnerLoading" class="pdf-view-loading">
      <el-progress :percentage="pageLoadedCount" :stroke-width="3" :show-text="false"></el-progress>
    </div>
    <div v-if="!loading" class="pdf-view-body" :style="{ height: pdfViewHeight - 50 + 'px' }">
      <transition name="el-fade-in-linear">
        <div
          v-show="isMenu"
          class="pdf-view-list"
          :style="{ flex: isFullScreen ? '0 0 247px' : '0 0 147px' }"
        >
          <el-scrollbar ref="menuScrollbar" class="pdf-scrollbar">
            <div
              v-for="(item, index) in pageTotal"
              :key="item"
              class="item"
              :class="{ active: currentPage === item }"
              @click="clickPageChange(index)"
            >
              <div
                class="pdf-box"
                :style="{
                  width: isFullScreen ? '200px' : '100px',
                  height: isFullScreen ? '200px' : '100px'
                }"
              >
                <pdf :src="laoclUrl" :page="item" class="vue-pdf-embed" />
              </div>
              <div class="num">{{ item }}</div>
            </div>
          </el-scrollbar>
        </div>
      </transition>
      <div class="pdf-view-content">
        <el-scrollbar ref="scrollPdfRef" class="pdf-scrollbar">
          <div class="pdf-view-arrow" :style="{ 'min-height': pdfViewHeight - 50 + 'px' }">
            <div v-for="item in pageTotal" :key="item" class="pdf-view-arrow__item">
              <pdf
                :src="laoclUrl"
                :page="item"
                class="vue-pdf-embed"
                :style="[{ width: contentScaleWidth + 'px' }]"
              />
            </div>
          </div>
        </el-scrollbar>
      </div>
    </div>

    <div class="vue-pdf-default">
      <pdf
        v-for="i in numPages"
        :key="i"
        :src="laoclUrl"
        :page="i"
        @num-pages="getTotalPage"
        @page-loaded="pageLoaded"
        @loaded="mountedLoaded"
      ></pdf>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import pdf from 'vue-pdf'
import eventVue from '../sectiobWatchEventVue.js'
export default {
  components: {
    pdf
  },
  props: {
    detailInfo: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      laoclUrl: '',
      numPages: 1,
      pdfViewHeight: 486, // 试图的高度

      thumbnailList: [],
      isMenu: true,
      loading: false,
      isFullScreen: false, // 是否全屏
      pageTotal: 1, // 获得总页数
      currentPage: 1, // 当前页
      activePage: 1, // 左侧选中的页面
      contentScaleWidth: 435, // 内容宽度
      pageScale: 1, // 放大系数 默认百分百
      seconds: 0, // 学习
      pageLoadedNumber: 0,
      timer: null,
      showSpinnerLoading: true
    }
  },
  computed: {
    ...mapState({
      getCurrentPlayItem: state => state.course.currentPlayItem
    }),
    pageLoadedCount() {
      let num = this.pageLoadedNumber || 0
      let total = this.numPages || 1
      return (num / total) * 100
    }
  },
  methods: {
    getPlayerFile() {
      clearInterval(this.timer)
      this.seconds = 0
      this.timer = null
      this.loading = true
      let class_id = this.detailInfo.course_type === 4 ? this.detailInfo.id : 0
      this.$api.getCourseSectionFileurl(
        this.getCurrentPlayItem.course_id,
        this.getCurrentPlayItem.id,
        {
          class_id: class_id
        },
        res => {
          const { data } = res
          // 当前播放定位
          this.$store.dispatch('course/setCurrentPlayPosition', {
            ...data.curr_position
          })
          if (data.url_type == 2) {
            this.getNumPages(data.fileurl_string)
          }
        }
      )
    },
    getNumPages(url) {
      var loadingTask = pdf.createLoadingTask({
        url: url,
        cMapUrl: 'https://unpkg.com/pdfjs-dist@2.0.943/cmaps/',
        cMapPacked: true
      })
      loadingTask.promise
        .then(pdf => {
          this.laoclUrl = loadingTask
          this.numPages = pdf.numPages
        })
        .catch(err => {
          console.error('pdf加载失败')
        })
    },
    changePdfPage(val) {
      if (val === 0 && this.currentPage > 1) {
        this.currentPage--
      }
      if (val === 1 && this.currentPage < this.pageTotal) {
        this.currentPage++
      }
      this.scrollTop(this.currentPage)
    },
    //跳转页面
    pageChange(val) {
      if (val > 0 && val <= this.pageTotal) {
        this.currentPage = val
      } else {
        this.currentPage = 1
      }
      this.scrollTop(this.currentPage)
    },
    // 更新当前页
    clickPageChange(index) {
      this.currentPage = index + 1
      this.scrollTop(this.currentPage)
    },
    // 获取到pdf总页数时触发 会传入总页数
    getTotalPage(page) {
      this.pageTotal = page
    },
    // 初始化加载完毕触发
    mountedLoaded() {
      setTimeout(() => {
        this.loading = false
      }, 500)
      this.timer = null
      clearInterval(this.timer)
      this.timer = setInterval(() => {
        this.seconds++
        if (this.seconds % 10 == 0) {
          this.addLearning()
        }
      }, 1000)
    },
    // 每加载完成一页时触发(初始化/翻页时均会触发)
    pageLoaded(page) {
      if (page > 1) {
        this.pageLoadedNumber = page
      }
      if (page >= this.pageTotal) {
        setTimeout(() => {
          this.showSpinnerLoading = false
        }, 600)
      }
    },
    // 点击缩放时触发
    scalePage(type) {
      // 改变缩放比例
      let sacle = 0
      if (type === 0) {
        if (this.pageScale === 0.8) return
        sacle = this.pageScale - 0.02
        this.contentScaleWidth = this.contentScaleWidth - this.pageScale * 10
      } else if (type === 1) {
        if (this.pageScale === 1.8) return
        sacle = this.pageScale + 0.02
        this.contentScaleWidth = this.contentScaleWidth + this.pageScale * 10
      } else if (type === 2) {
        sacle = 1
        this.contentScaleWidth = this.isFullScreen ? 950 : 435
      }
      // 可能会涉及js的精度损失 保留一位小数即可
      this.pageScale = Number(sacle.toFixed(2))
    },
    // 菜单
    handleMenuChange() {
      this.isMenu = !this.isMenu
    },
    changeFullScreen() {
      this.isFullScreen = !this.isFullScreen
      if (this.isFullScreen) {
        document.body.classList.add('el-popup-parent--hidden')
        this.pdfViewHeight = window.innerHeight
        this.contentScaleWidth = 950
      } else {
        document.body.classList.remove('el-popup-parent--hidden')
        this.pdfViewHeight = 486
        this.contentScaleWidth = 435
      }
      this.pageScale = 1
    },
    // 添加学习记录
    addLearning() {
      this.$api.createCourseRecord({
        course_id: this.getCurrentPlayItem.course_id,
        section_id: this.getCurrentPlayItem.id,
        current_time: this.seconds
      })
    },
    // el-scrollbar内滚动条滚动时
    scrollPdf() {
      // 获取 el-scrollbar 的容器元素
      const container = document.querySelector('.pdf-view-content .pdf-view-arrow__item')

      // 获取容器的高度
      const containerHeight = container.offsetHeight + 10

      // 获取滚动条的高度
      const scrollbarHeight = this.$refs.scrollPdfRef.wrap.scrollTop

      // 计算滚动到几页
      const totalPages = Math.ceil(scrollbarHeight / containerHeight)
      if (totalPages > 0 && this.currentPage != totalPages) {
        this.currentPage = totalPages
        this.scrollMenu()
      }
    },
    // 跳转到指定位置
    scrollTop(index) {
      // 获取 el-scrollbar 的容器元素
      const container = document.querySelector('.pdf-view-content .pdf-view-arrow__item')

      // 获取容器的高度
      const containerHeight = container.offsetHeight + 11
      this.$refs.scrollPdfRef.wrap.scrollTop = (index - 1) * containerHeight
    },
    scrollMenu() {
      const container = $('.pdf-view-list .item')[this.currentPage - 1]
      const scrollbar = this.$refs.menuScrollbar
      const clientHeight = scrollbar.wrap.clientHeight
      const scrollTop = scrollbar.wrap.scrollTop
      if (container.offsetTop < scrollTop) {
        scrollbar.wrap.scrollTop = container.offsetTop - 4
      }
      if (container.offsetTop > scrollTop + clientHeight) {
        scrollbar.wrap.scrollTop = container.offsetTop - 4
      }
    }
  },
  mounted() {
    this.getPlayerFile()
    eventVue.$on('sendSectionBybus', () => {
      this.getPlayerFile()
    })
    // 监听el-scrollbar内滚动条的滚动
    this.$refs.scrollPdfRef.wrap.addEventListener('scroll', this.scrollPdf)
  },
  beforeDestroy() {
    clearInterval(this.timer)
  }
}
</script>

<style lang="scss" scoped>
.pdf-view {
  background: #000000;
  position: relative;
  &.pdf-view-fixed {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 9999;
  }

  .pdf-view-header {
    height: 50px;
    display: flex;
    align-items: center;
    position: relative;
    background: #1a1a1a;
    .pdf-menu {
      margin-left: 15px;
      width: 24px;
      height: 24px;
      font-size: 18px;
      color: #ffffff;
      border-radius: 2px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      &.active {
        background: rgba(255 255 255 / 50%);
      }
    }
    .pdf-page {
      display: flex;
      align-items: center;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      .icon {
        color: #fff;
        font-size: 14px;
        padding: 5px 6px;
        cursor: pointer;
      }
      .el-icon-arrow-left {
        margin-right: 24px;
      }
      .el-icon-arrow-right {
        margin-left: 24px;
      }
      .text {
        font-size: 13px;
        font-weight: 400;
        color: #ffffff;
        margin-left: 4px;
      }
      ::v-deep .el-input__inner {
        width: 40px;
        height: 20px;
        padding: 0;
        font-size: 13px;
        font-weight: 400;
        color: #ffffff;
        text-align: center;
        background: #252525;
        border-radius: 2px;
        border: 1px solid #555555;
      }
    }
    .pdf-scale {
      display: flex;
      align-items: center;
      margin-left: auto;
      .icon {
        width: 16px;
        height: 16px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        color: #ffffff;
        background: rgba(255, 255, 255, 0.09);
        border-radius: 100%;
        cursor: pointer;
      }
      .text {
        font-size: 13px;
        font-weight: 400;
        color: #ffffff;
        margin: 0 10px;
      }
    }
    .pdf-full {
      width: 24px;
      height: 24px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 14px;
      color: #ffffff;
      background: rgba(255, 255, 255, 0.1);
      border-radius: 2px;
      cursor: pointer;
      margin-right: 30px;
      margin-left: 40px;
    }
  }
  .pdf-view-loading {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    z-index: 99;
    overflow: hidden;
    height: 3px;
    ::v-deep .el-progress-bar__outer {
      background-color: transparent;
    }
  }
  .pdf-view-body {
    display: flex;
    .pdf-view-list {
      height: 100%;
      padding: 6px 0;
      box-sizing: border-box;
      .pdf-scrollbar {
        height: 100%;
        ::v-deep .el-scrollbar__wrap {
          overflow-x: auto;
          overflow-x: hidden;
        }
        ::v-deep .el-scrollbar__bar {
          background-color: #303133;
        }
        ::v-deep .el-scrollbar__bar.is-vertical {
          opacity: 1;
        }
        ::v-deep .el-scrollbar__bar.is-horizontal {
          opacity: 0;
        }
        ::v-deep .el-scrollbar__thumb {
          background-color: #909399;
        }
      }
      .item + .item {
        margin-top: 10rpx;
      }
      .item {
        position: relative;
        cursor: pointer;
        .pdf-box {
          margin: 0 auto;
          padding: 5px;
          .vue-pdf-embed {
            width: 100%;
            height: 100%;
            overflow: hidden;
          }
        }
        .num {
          font-size: 12px;
          font-weight: 400;
          color: #b7bac1;
          line-height: 18px;
          text-align: center;
        }
        &:hover,
        &.active {
          .pdf-box {
            background: rgba(255 255 255 / 50%);
          }
        }
      }
    }

    .pdf-view-content {
      flex: 1;
      min-width: 0;
      height: 100%;
      .pdf-scrollbar {
        height: 100%;
        ::v-deep .el-scrollbar__wrap {
          overflow-x: auto;
        }
        ::v-deep .el-scrollbar__bar {
          background-color: #303133;
        }
        ::v-deep .el-scrollbar__bar.is-vertical {
          opacity: 1;
        }
        ::v-deep .el-scrollbar__bar.is-horizontal {
          opacity: 0;
        }
        ::v-deep .el-scrollbar__thumb {
          background-color: #909399;
        }
      }
      .pdf-view-arrow {
        width: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        .vue-pdf-embed {
          transform-origin: center;
        }
        .pdf-view-arrow__item {
          margin-bottom: 10px;
        }
      }
    }
  }
}
.pdf-preview-arrow {
  color: #fff;
  display: flex;
}

.vue-pdf-default {
  opacity: 0;
  position: absolute;
  left: -100%;
  top: -100%;
  display: none;
}
</style>
